
const app = getApp()
Page({
    data: {
      remote_src: app.globalData.remote_src,
      selectedImages: [],
      maxImages: 9,
      currentTab: 'other',
      selectedPeople: '1-3',
      selectedCost: 'free',
      selectedType: '拍照',
      id: -1,
      title: '2',
      locationInfo: null,  // 存储完整的位置信息
      days: [],
      showTimePicker: false,
      showEndTimePicker: false,
      dialogButtons: [{text: '下一步'}], 
      endDialogButtons: [{text: '确定'}],
      startTimeText: '',
      endTimeText: '',
      timeText: '时间',
      hours: Array.from({length: 24}, (_, i) => String(i).padStart(2, '0')),
      minutes: Array.from({length: 60}, (_, i) => String(i).padStart(2, '0')),
      timePickerValue: [0, 0, 0],
      showActivityType: false,
      activityTypes: [
        { name: '拍照', selected: false },
        { name: '探店', selected: false },
        { name: '约饭', selected: false },
        { name: '爬山', selected: false },
        { name: '露营', selected: false },
        { name: '户外', selected: false },
        { name: '运动', selected: false },
        { name: '做美甲', selected: false },
        { name: '看电影', selected: false },
        { name: '逛街', selected: false },
        { name: '旅游', selected: false },
        { name: '看展', selected: false },
        { name: '撸猫撸狗', selected: false },
        { name: '其他', selected: false }
      ],
      showPeopleInput: false,
      inputPeople: ''
    },
    previewImage(e) {
      const index = e.currentTarget.dataset.index;
      const current = this.data.selectedImages[index];
      
      wx.previewImage({
        current: current,
        urls: this.data.selectedImages
      });
    },
    // 显示人数输入框
    showPeopleInput() {
      this.setData({
        showPeopleInput: true
      });
    },

    // 关闭人数输入框
    closePeopleInput() {
      this.setData({
        showPeopleInput: false
      });
    },
    // 监听人数输入
    onPeopleInput(e) {
      this.setData({
        inputPeople: e.detail.value
      });
    },

    // 确认人数选择
    confirmPeople() {
      if (this.data.inputPeople) {
        this.setData({
          selectedPeople: this.data.inputPeople,
          showPeopleInput: false
        });
      }
    },

    // 显示更多活动类型
    showMoreTypes() {
      this.setData({
        showActivityType: true
      });
    },
      // 关闭活动类型选择框
    closeActivityType() {
      this.setData({
        showActivityType: false
      });
    },

  // 选择活动类型
  selectActivityType(e) {
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type;
    const types = this.data.activityTypes.map((item, idx) => ({
      ...item,
      selected: idx === index
    }));
    
    this.setData({
      activityTypes: types,
      selectedType: type
    });
  },

  // 确认活动类型选择
  confirmActivityType() {
    const selectedType = this.data.activityTypes.find(type => type.selected);
    if (selectedType) {
      this.setData({
        selectedType: selectedType.name,
        showActivityType: false
      });
    }
  },
  loadDateData(){
    // 生成未来7天的日期
    const days = [];
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const now = new Date();
    
    for(let i = 0; i < 7; i++) {
      const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const weekday = weekdays[date.getDay()];
      days.push(`${month}月${day}日 ${weekday}`);
    }
    this.setData({ days });
  },
  onLoad(options) {
     this.loadDateData();
     const decodedOptions = {};
     for (let key in options) {
      if (key === 'address' || key === "images") {
         decodedOptions[key] = JSON.parse(decodeURIComponent(options[key]));
       } else {
         decodedOptions[key] = decodeURIComponent(options[key]);
       }
     }
     console.log(decodedOptions);
     this.setData ({
      id: decodedOptions.id,
      title: decodedOptions.name,
      content: decodedOptions.content,
      selectedImages: decodedOptions.images,
      selectedType: decodedOptions.type,
      locationInfo: {
        name: decodedOptions.address.address,
        address: decodedOptions.address.name,
        latitude: decodedOptions.address.latitude,
        longitude: decodedOptions.address.longitude
      },
      startTimeText: decodedOptions.start_time,
      endTimeText: decodedOptions.end_time,
      timeText: `${decodedOptions.start_time} - ${decodedOptions.end_time}`,
      selectedPeople: decodedOptions.people_number,
      selectedCost: decodedOptions.fee,
    });
  },
  
    chooseLocation() {
      const { locationInfo } = this.data;
      wx.chooseLocation({
        latitude: locationInfo ? locationInfo.latitude : 22.54286,  // 默认深圳纬度
        longitude: locationInfo ? locationInfo.longitude : 114.05956,  // 默认深圳经度
        success: (res) => {
          console.log('选择地址成功', res);
          if (!res.name) {
            wx.showToast({
              title: '请选择具体地点',
              icon: 'none'
            });
            return;
          }
          this.setData({
            locationInfo: {
              name: res.name,
              address: res.address,
              latitude: res.latitude,
              longitude: res.longitude
            }
          });
        },
        fail: (err) => {
          console.log('选择地址失败', err);
        }
      });
    },
    chooseTime() {
      this.setData({
        showTimePicker: true
      });
    },
    onTimePickerChange(e) {
      console.log('选择时间');
      const val = e.detail.value;
      this.setData({
        timePickerValue: val
      });
    },
    onStartTimePickerAction(e) {
      const { days, hours, minutes, timePickerValue } = this.data;
      // 解析日期字符串，例如："1月1日 周一"
      const dayStr = days[timePickerValue[0]];
      const matches = dayStr.match(/(\d+)月(\d+)日/);
      const currentYear = new Date().getFullYear();
      
      // 构建完整的日期时间字符串
      const selectedTime = `${currentYear}-${String(matches[1]).padStart(2, '0')}-${String(matches[2]).padStart(2, '0')} ${hours[timePickerValue[1]]}:${minutes[timePickerValue[2]]}:00`;
      
      this.setData({
        startTimeText: selectedTime,
        showTimePicker: false,
        showEndTimePicker: true
      });
    },

    onEndTimePickerAction(e) {
      const { days, hours, minutes, timePickerValue } = this.data;
      // 解析日期字符串
      const dayStr = days[timePickerValue[0]];
      const matches = dayStr.match(/(\d+)月(\d+)日/);
      const currentYear = new Date().getFullYear();
      
      // 构建完整的日期时间字符串
      const selectedTime = `${currentYear}-${String(matches[1]).padStart(2, '0')}-${String(matches[2]).padStart(2, '0')} ${hours[timePickerValue[1]]}:${minutes[timePickerValue[2]]}:00`;
      
      this.setData({
        endTimeText: selectedTime,
        showEndTimePicker: false,
        timeText: `${this.data.startTimeText} - ${selectedTime}`
      });
    },
  
    switchTab(e) {
      const tab = e.currentTarget.dataset.tab;
      this.setData({ currentTab: tab });
    },
  
    selectPeople(e) {
      const value = e.currentTarget.dataset.value;
      this.setData({ selectedPeople: value });
    },
  
    selectCost(e) {
      const value = e.currentTarget.dataset.value;
      this.setData({ selectedCost: value });
    },
  
    selectType(e) {
      const value = e.currentTarget.dataset.value;
      this.setData({ selectedType: value });
    },
    onContentInput(e) {
      this.setData({ content: e.detail.value });
    },
    chooseImage() {
      const remainCount = this.data.maxImages - this.data.selectedImages.length;
      if (remainCount <= 0) {
        wx.showToast({
          title: '最多选择9张图片',
          icon: 'none'
        });
        return;
      }
      wx.chooseImage({
        count: remainCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadImages(res.tempFilePaths);
        }
      });
    },
      // 添加上传图片方法
      uploadImages(tempFilePaths) {
              wx.showLoading({
                title: '上传图片中...',
                mask: true
              });
              const uploadPromises = tempFilePaths.map(path => {
                return new Promise((resolve, reject) => {
                  const url = getApp().globalData.onlineService + '/api/infra/file';
                  wx.uploadFile({
                    url: url,
                    filePath: path,
                    name: 'file',
                    success: res => {
                      const data = JSON.parse(res.data);
                      console.log(data);
                      if (data.code === 200) {
                        resolve(url + "?filename=" + data.filename);
                      } else {
                        reject(new Error(data.msg || '上传失败'));
                      }
                    },
                    fail: err => reject(err)
                  });
                });
              });
              Promise.all(uploadPromises)
                .then(urls => {
                  const newImages = [...this.data.selectedImages, ...urls];
                  this.setData({
                    selectedImages: newImages
                  });
                  wx.hideLoading();
                })
                .catch(err => {
                  console.error('上传图片失败：', err);
                  wx.hideLoading();
                  wx.showToast({
                    title: '上传图片失败',
                    icon: 'none'
                  });
                });
        },
    onTitleInput(e) {
      this.setData({ title: e.detail.value });
    },
    onContentInput(e) {
      this.setData({ content: e.detail.value });
    },
    // Add this function to delete images
    deleteImage(e) {
        const index = e.currentTarget.dataset.index;
        const newImages = this.data.selectedImages.filter((_, i) => i !== index);
        this.setData({
          selectedImages: newImages
        });
    },
    publishActivity() {
      // 数据验证
      if (!this.data.title.trim()) {
        wx.showToast({
          title: '请输入活动标题',
          icon: 'none'
        });
        return;
      }

      if (this.data.selectedImages.length === 0) {
        wx.showToast({
          title: '请至少上传一张图片',
          icon: 'none'
        });
        return;
      }

      if (!this.data.locationInfo) {
        wx.showToast({
          title: '请选择活动地点',
          icon: 'none'
        });
        return;
      }

      if (this.data.timeText === '时间') {
        wx.showToast({
          title: '请选择活动时间',
          icon: 'none'
        });
        return;
      }

      // 显示加载提示
      wx.showLoading({
        title: '发布中...',
        mask: true
      });

      // 构建活动数据
      const activityData = {
        activity_id: this.data.id,
        name: this.data.title,
        content: this.data.content,
        images: this.data.selectedImages,
        type: this.data.selectedType,
        address_name: this.data.locationInfo.address,
        address: this.data.locationInfo.name,
        longitude: this.data.locationInfo.longitude,
        latitude: this.data.locationInfo.latitude,
        start_time: this.data.startTimeText,
        end_time: this.data.endTimeText,
        people_number: this.data.selectedPeople,
        fee: this.data.selectedCost,
      };
      console.log('活动数据：', activityData);
      const token = getApp().globalData.userInfo.token;
      console.log(token);
      const requset_url = getApp().globalData.onlineService + '/api/activity/activity';
      wx.request({
        url:  requset_url,
        method: 'PUT',
        header: {
          'Authorization': 'Bearer '+ token,
          'content-type': 'application/json'
        },
        data: activityData,
        success: (res) => {
          wx.hideLoading();
          console.log('返回结果：', res.data);
          if (res.data.code === 200) {
              // 获取上上页实例
              const pages = getCurrentPages();
              const prevPage1 = pages[pages.length - 3];
              const prevPage2 = pages[pages.length - 2];
              
              // 更新上一页数据
              if (prevPage2) {
                // 更新上一页的活动详情
                prevPage2.setData({
                  activityInfo: {
                    id: this.data.id,
                    name: this.data.title,
                    content: this.data.content,
                    images: this.data.selectedImages,
                    type: this.data.selectedType,
                    address: this.data.locationInfo,
                    start_time: this.data.startTimeText,
                    end_time: this.data.endTimeText,
                    people_number: this.data.selectedPeople,
                    fee: this.data.selectedCost,
                  }
              
                });
              }
              
              // 更新列表页数据
              if (prevPage1) {
                prevPage1.loadCreatedList();
              }
             wx.showToast({
               title: '修改成功',
               icon: 'success',
               duration: 2000
             });
             
             setTimeout(() => {
               wx.navigateBack();
             }, 2000);
          } else {
            wx.showToast({
              title: res.data.msg || '发布失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          console.error('发布活动失败：', err);
        }
      });
      
    }
  });